package controllers

import (
	"app/models"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
)

type GuestController struct {
	beego.Controller
}
type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *GuestController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	err := models.DB.Model(&models.Guest{}).Count(&count).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "总数查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	offset := (page - 1) * size
	var guest []models.Guest
	err = models.DB.Debug().Offset(offset).Limit(size).Find(&guest).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	pageData := make(map[string]interface{})
	pageData["count"] = count
	pageData["guest"] = guest
	c.Data["json"] = JsonRes{
		Code: 200,
		Msg:  "查询成功",
		Data: pageData,
	}
	c.ServeJSON()
}

// redis的详情
func (c *GuestController) Info() {
	id, _ := c.GetInt("id")
	key := "anchor-" + strconv.Itoa(id)
	// 缓存原理  判断缓存中是否有数据， 有的话直接读取缓存， 没有的话查询数据库， 并且存入缓存
	val, err := models.Rdb.Get(key).Result() // 判断是否 获取缓存
	var guest models.Guest
	if err != nil {
		err = models.DB.Model(&models.Guest{}).Where("ID = ?", id).First(&guest).Error
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  "详情展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		//  存入缓存
		jsonByte, _ := json.Marshal(guest) //结构体转切片
		value := string(jsonByte)
		models.Rdb.Set(key, value, 0) //持久保存就是0
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "详情展示成功-mysql",
			Data: guest,
		}
		c.ServeJSON()
	} else {
		json.Unmarshal([]byte(val), &guest) //字符串转字符切片
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "详情查询成功-redis",
			Data: guest,
		}
		c.ServeJSON()

	}

}
